package com.swmsss.android_message_receiver;

import java.io.IOException;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;

import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.telephony.SmsMessage;
import android.util.Log;
import android.widget.Toast;

public class MessageReceiver extends BroadcastReceiver {
	
	private static final String tag = "MessageReceiver";
	private static final String address = "http://210.118.64.169/db/insert_message.php";
	
	private Context mContext;
	SharedPreferences pref;
	
	@Override
	public void onReceive(Context context, Intent intent) {
		// TODO Auto-generated method stub
		mContext = context;
		
		//if switch is off, do nothing
        pref = mContext.getSharedPreferences("com.swmsss.android_message_receiver", Activity.MODE_PRIVATE);
        boolean bReceiveMessage = pref.getBoolean("ReceiveMessages", false);
        if(bReceiveMessage == false) return;
		
		Bundle bundle = intent.getExtras();
		SmsMessage[] messages = null;
		
		if(bundle != null) {
			String originating_address, message_body;
			
			Object[] pdus = (Object[])bundle.get("pdus");
			messages = new SmsMessage[pdus.length];
			
			if(messages.length == 1) {
				Log.i(tag, "Received a message!");
			} else {
				Log.i(tag, "Received " + messages.length + " messages!");
			}
			
			for(int i=0; i<messages.length;  i++) {
				messages[i] = SmsMessage.createFromPdu((byte[])pdus[i]);
				
				originating_address = messages[i].getOriginatingAddress();
				message_body = messages[i].getMessageBody().toString();
				
				//log
				if(messages.length != 1) {
					Log.i(tag, "message["+i+"]");
				}
				Log.i(tag, "originating_address: " + originating_address);
				Log.i(tag, "message_body: " + message_body);
				
				//toast
				String text = "Received a message from " + originating_address + ".\n" + message_body;
				Toast.makeText(context, text, Toast.LENGTH_SHORT).show();
				
				//insert this message into database
				insertMessageIntoDatabase(originating_address, message_body);
			}
		}
	}
	
	public void insertMessageIntoDatabase(String originating_address, String message_body) {
		String message_body_converted = convertStringForURL(message_body);
		
		String url = address;
		url += "?originating_address=" + originating_address;
		url += "&message_body=" + message_body_converted;
		
		Log.i(tag, "insert message url : " + url);
		
		HttpClient httpClient = new DefaultHttpClient();
		HttpGet getRequest = new HttpGet(url);
		
		try {
			HttpResponse httpGetResponse = httpClient.execute(getRequest);
			HttpEntity httpGetResponseEntity = httpGetResponse.getEntity();
			
			String responseMessage = new String(EntityUtils.toByteArray(httpGetResponseEntity), "utf-8");
			if(responseMessage.equals("success")) {
				Log.i(tag, "Insert Message Success!");

				//toast
				String text = "Inserted a message into databse.";
				Toast.makeText(mContext, text, Toast.LENGTH_SHORT).show();
				
			} else {
				Log.e(tag, "Insert Message Failed! (1)");

			}
		} catch(ClientProtocolException e) {
			e.printStackTrace();
			//
			Log.e(tag, "Insert Message Failed! (2)");
			//

		} catch(IOException e) {
			e.printStackTrace();
			//
			Log.e(tag, "Insert Message Failed! (3)");
			//

		}
	}

	public String convertStringForURL(String str) {
		String converted_str;
		
		// ' ' -> %20
		converted_str = str.replaceAll(" ", "%20");
		
		// '\n' -> %20
		converted_str = converted_str.replaceAll("\n", "%20");
		
		// '\r' -> %20
		converted_str = converted_str.replaceAll("\r", "%20");
		
		return converted_str;
	}
}
